package com.pay.plat.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pay.constant.Constant;
import com.pay.entity.SysMenus;
import com.pay.entity.SysRole;
import com.pay.entity.SysRoleMenu;
import com.pay.entity.SysUser;
import com.pay.exception.ServiceException;
import com.pay.mapper.SysMenusMapper;
import com.pay.plat.service.ManagerService;
import com.pay.service.ISysMenusService;
import com.pay.service.ISysRoleMenuService;
import com.pay.service.ISysRoleService;
import com.pay.service.ISysUserService;
import com.pay.utils.FunctionUtils;
import com.pay.utils.MD5Util;
import com.pay.utils.ResponseData;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;

@Service
public class ManagerServiceImpl implements ManagerService{

	@Autowired
	private ISysMenusService sysMenusService ;
	
	@Autowired
	private ISysUserService sysUserService ;
	
	@Autowired
	private ISysRoleService sysRoleService ;
	
	@Autowired
	private ISysRoleMenuService sysRoleMenusService ;
	
	@Autowired
	private SysMenusMapper sysMenusMapper ;
	
	/**
	 * 实例锁
	 */
	private Lock lock = new ReentrantLock() ;
	
	@Override
	public List<SysMenus> getMenus() {
		QueryWrapper<SysMenus> ew = new QueryWrapper<SysMenus>();
		ew.eq("parentid", 0) ;
		ew.eq("ismenu", Constant.is_menu) ; 
		ew.eq("status", Constant.menu_effective) ;
		ew.orderByAsc("sort") ;
		List<SysMenus> menus = sysMenusService.list(ew); //获取主菜单
		for (SysMenus sysMenus : menus) {
			ew = new QueryWrapper<SysMenus>() ;
			ew.eq("parentid", sysMenus.getId()) ;
			ew.eq("ismenu", Constant.is_menu) ;
			ew.eq("status", Constant.menu_effective) ;
			ew.orderByAsc("sort") ;
			List<SysMenus> childs = sysMenusService.list(ew) ; //获取子菜单
			sysMenus.setChilds(childs); 
		}
		return menus ;
	}

	@Override
	public Map<String, String> getPermissions(Integer loginId) {
		HashMap<String, String> permissions = new HashMap<String,String>();
		SysUser user = sysUserService.getById(loginId);
		SysRole role = sysRoleService.getById(user.getRoleid());
		SysRoleMenu roleMenu = sysRoleMenusService.getOne(new QueryWrapper<SysRoleMenu>().eq("roleid", role.getId()));
		List<SysMenus> menus = sysMenusService.list(new QueryWrapper<SysMenus>().in("id",FunctionUtils.getList(roleMenu.getMenuids().split(","))));
		for (SysMenus sysMenus : menus) {
			permissions.put(sysMenus.getUrl(), sysMenus.getMenuname()) ;
		}
		return permissions ;
	}

	@Override
	public List<SysUser> getUserList(SysUser sysUser) {
		QueryWrapper<SysUser> ew = new QueryWrapper<SysUser>();
		if(sysUser.getDatemin() != null && sysUser.getDatemax() != null) {
			ew.between("createtime", sysUser.getDatemin(), DateUtil.endOfDay(sysUser.getDatemax()).toJdkDate()) ;
		}
		if(StrUtil.isNotBlank(sysUser.getName())) {
			ew.like("login", sysUser.getName()) ;
		}
		List<SysUser> users = sysUserService.list(ew);
		for (SysUser user : users) {
			SysRole role = sysRoleService.getById(user.getRoleid());
			user.setSysRole(role);
		}
		return users ;
	}

	@Override
	public ResponseData doUserAdd(SysUser sysUser) {
		try {
			lock.lock(); 
			if(StrUtil.isBlank(sysUser.getLogin())) {
				return ResponseData.baseError("必须填写登录账号") ;
			}
			SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("login", sysUser.getLogin())) ;
			if(user != null) {
				return ResponseData.baseError("该管理员已经存在") ;
			}
			if(StrUtil.isBlank(sysUser.getName())) {
				return ResponseData.baseError("必须填写管理员名称") ;
			}
			if(StrUtil.isBlank(sysUser.getPassword())) {
				return ResponseData.baseError("必须填写密码") ; 
			}
			if(StrUtil.isBlank(sysUser.getPhone())) {
				return ResponseData.baseError("必须填写手机号码") ; 
			}
			if(sysUser.getRoleid() == null) {
				return ResponseData.baseError("必须选择一个角色") ;
			}
			String md5Pass = MD5Util.md5Hex(sysUser.getPassword()) ;
			sysUser.setPassword(md5Pass) ;
			boolean result = sysUserService.save(sysUser);
			if(!result) {
				throw new ServiceException("业务异常") ;
			}
		}catch(Exception e) {
			throw e ;
		}finally {
			lock.unlock(); 
		}
		return ResponseData.ok() ;
	}

	@Override
	public ResponseData doUserDelete(String ids,Integer loginId) {
		if(StrUtil.isBlank(ids)) {
			return ResponseData.baseError("必须选择一个要删除的管理员") ;
		}
		List<Integer> idList = FunctionUtils.getList(ids.split(","));
		QueryWrapper<SysUser> ew = new QueryWrapper<SysUser>();
		ew.in("id", idList) ; //删除选中的管理员
		ew.ne("id", loginId) ; //不能删除当前登录人
		ew.ne("id", "1") ; // 不能删除1号管理员
		sysUserService.remove(ew) ;
		return ResponseData.ok() ;
	}

	@Override
	public ResponseData doUserEdit(SysUser sysUser) {
		sysUser.setLogin(null);
		if(sysUser.getName() != null && "".equals(sysUser.getName())) {
			return ResponseData.baseError("名称不能为空") ;
		}
		if(sysUser.getName() != null && !Validator.isMobile(sysUser.getPhone())) {
			return ResponseData.baseError("手机号码格式不正确") ;
		}
		if(StrUtil.isNotBlank(sysUser.getPassword())) {
			String md5Pass = MD5Util.md5Hex(sysUser.getPassword()) ;
			sysUser.setPassword(md5Pass); 
		}else {
			sysUser.setPassword(null); 
		}
		boolean result = sysUserService.updateById(sysUser);
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		return ResponseData.ok() ;
	}

	@Override
	public List<SysRole> getRoleList() {
		List<SysRole> roles = sysRoleService.list(null);
		for (SysRole sysRole : roles) {
			List<SysUser> users = sysUserService.list(new QueryWrapper<SysUser>().eq("roleid", sysRole.getId()));
			sysRole.setUsers(users);
		}
		return roles ;
	}

	@Override
	public ResponseData doRoleDelete(String ids) {
		if(StrUtil.isBlank(ids)) {
			return ResponseData.baseError("请选择你要删除的角色") ;
		}
		List<Integer> idList = FunctionUtils.getList(ids.split(",")) ;
		int userCount = sysUserService.count(new QueryWrapper<SysUser>().in("roleid", idList));
		if(userCount != 0) {
			return ResponseData.baseError("删除的角色还存在管理员") ;
		}
		boolean result = sysRoleService.removeByIds(idList);
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		return ResponseData.ok();
	}

	@Override
	public List<SysMenus> getResource() {
		List<SysMenus> menusList = sysMenusService.list(new QueryWrapper<SysMenus>().eq("parentid", 0).eq("status", Constant.menu_effective)); //先查询出所有的一级菜单
		for (SysMenus sysMenus : menusList) {
			List<SysMenus> childMenusList = sysMenusService.list(new QueryWrapper<SysMenus>().eq("parentid", sysMenus.getId()).eq("status", Constant.menu_effective)) ; //子菜单
			for (SysMenus childMenus : childMenusList) {
				List<SysMenus> childResource = sysMenusService.list(new QueryWrapper<SysMenus>().eq("parentid", childMenus.getId()).eq("status", Constant.menu_effective)) ; //子资源
				childMenus.setChilds(childResource);
			}
			sysMenus.setChilds(childMenusList); 
		}
		return menusList ;
	}

	@Override
	public ResponseData doRoleAdd(SysRole sysRole,String menuids) {
		if(StrUtil.isBlank(sysRole.getName())) {
			return ResponseData.baseError("角色名称不能为空") ;
		}
		boolean result = sysRoleService.save(sysRole); //添加角色
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		SysRoleMenu roleMenu = new SysRoleMenu();
		roleMenu.setMenuids(menuids);
		roleMenu.setRoleid(sysRole.getId()); 
		result = sysRoleMenusService.save(roleMenu) ;
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		return ResponseData.ok() ;
	}

	@Override
	public ResponseData doRoleEdit(SysRole sysRole, String menuids) {
		if(1 == sysRole.getId()) {
			//超级管理员角色
			//不可进行编辑状态
			sysRole.setStatus(null);
		}
		if(sysRole.getName() != null && "".equals(sysRole.getName())) {
			return ResponseData.baseError("角色名称不能为空") ;
		}
		boolean result = sysRoleService.updateById(sysRole); //编辑角色
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		SysRoleMenu roleMenu = sysRoleMenusService.getByRoleid(sysRole.getId());
		roleMenu.setMenuids(menuids);
		result = sysRoleMenusService.updateById(roleMenu) ;
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		return ResponseData.ok() ;
	}

	@Override
	public SysRole getRoleInfo(Integer id) {
		SysRole role = sysRoleService.getById(id);
		SysRoleMenu roleMenu = sysRoleMenusService.getById(role.getId()); 
		role.setRoleMenu(roleMenu);
		
		return role ;
	}

	@Override
	public List<SysMenus> getResourceByRoleid(Integer id) {
		List<SysMenus> menusList = sysMenusMapper.getResourceByRoleid(id,0);
		for (SysMenus sysMenus : menusList) {
			List<SysMenus> childMenus = sysMenusMapper.getResourceByRoleid(id,sysMenus.getId());
			for (SysMenus childMenu : childMenus) {
				List<SysMenus> childResource = sysMenusMapper.getResourceByRoleid(id,childMenu.getId());
				childMenu.setChilds(childResource);
			}
			sysMenus.setChilds(childMenus);
		}
		return menusList ;
	}

	@Override
	public ResponseData doEditPass(Integer loginId, String origin, String newPass) {
		if(StrUtil.isBlank(origin)) {
			return ResponseData.baseError("原始密码不能为空") ;
		}
		if(StrUtil.isBlank(newPass)) {
			return ResponseData.baseError("新密码不能为空") ;
		}
		SysUser user = sysUserService.getById(loginId);
		String md5Origin = MD5Util.md5Hex(origin) ;
		if(!user.getPassword().equals(md5Origin)) {
			return ResponseData.baseError("原始密码错误") ;
		}
		String md5NewPass = MD5Util.md5Hex(newPass) ;
		user.setPassword(md5NewPass);
		boolean result = sysUserService.updateById(user);
		if(!result) {
			throw new ServiceException("业务异常") ;
		}
		return ResponseData.ok() ;
	}	

}
